<?php

namespace App\Services;

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use App\Models\Activity;
use App\Models\User;
use App\Models\UserDraw;
use App\Models\UserCoupon;

class ActivityService
{
    public function getDrawRecord(Activity $activity, User $user)
    {
        $record = UserDraw::where('activity_id', $activity->id)->where('user_id', $user->id)->whereNull('draw_at')->first();
        if (!$record) {
            throw_invalid_request_exception('activity-has-no-times');
        }
        return $record;
    }

    //抽奖
    public function draw(Activity $activity, User $user)
    {
        $record = DB::transaction(function () use ($activity, $user) {
            $now = Carbon::now();
            $record = $this->getDrawRecord($activity, $user);
            $prize = $this->extract($activity);

            if ($prize && $prize->decreaseStock() <= 0) {
                $record->reason = '奖品[ID:' . $prize->id . ']库存不足';
                $prize = null;
            }

            //如果是卡券类型奖品，自动发券
            if ($prize && $prize->type == 'coupon') {
                $due_at = date('Y-m-d H:i:s', strtotime($prize->due_at));
                $valid_at = date('Y-m-d H:i:s', strtotime($prize->valid_at));
                $coupon = app('CouponService')->increase($user->id, $prize->name, $record->customerInfo->dealer_id, UserCoupon::TYPE_PRIZE, $record->id, $due_at, $valid_at);
                $prize->setAttribute('coupon_id', $coupon->id);
            }

            $record->draw_at = $now;
            $record->prize = $prize ? $prize->toArray() : $prize;
            $record->save();

            return $record;
        });
        return $record;
    }

    //抽取
    public function extract($activity)
    {
        $prizes = $activity->prizes;
        $num = 0;
        $number = mt_rand(1, 1000000);
        foreach ($prizes as $prize) {
            $num += intval($prize->probability * 10000);
            if ($number <= $num) {
                return $prize;
            }
        }
        return null;
    }
}
